extends Node

## 战斗状态检测器
## 用于检测战斗的开始和结束，并发送相应事件

## 战斗状态
enum BattleState {
	IDLE,      # 空闲状态
	BATTLE     # 战斗状态
}

## 当前战斗状态
var current_battle_state: BattleState = BattleState.IDLE

## 战斗检测计时器
var battle_detection_timer: Timer

## 战斗持续时间阈值（秒）
const BATTLE_DURATION_THRESHOLD = 3.0

## 战斗状态持续时间
var battle_state_duration: float = 0.0

## 是否检测到敌人
var enemy_detected: bool = false

func _ready() -> void:
	# 创建战斗检测计时器
	battle_detection_timer = Timer.new()
	battle_detection_timer.wait_time = 0.5  # 每0.5秒检测一次
	battle_detection_timer.one_shot = false
	battle_detection_timer.timeout.connect(_on_battle_detection_timer_timeout)
	add_child(battle_detection_timer)
	
	# 启动检测计时器
	battle_detection_timer.start()
	
	print("战斗状态检测器已初始化")

## 战斗检测计时器超时事件
func _on_battle_detection_timer_timeout() -> void:
	_check_battle_state()

## 检查战斗状态
func _check_battle_state() -> void:
	var new_battle_state = _determine_battle_state()
	
	if new_battle_state != current_battle_state:
		_handle_battle_state_change(new_battle_state)
	
	current_battle_state = new_battle_state

## 确定战斗状态
func _determine_battle_state() -> BattleState:
	# 检查是否有敌人在场景中
	var enemies = get_tree().get_nodes_in_group("enemy")
	var boss_enemies = get_tree().get_nodes_in_group("boss")
	
	# 如果有敌人或Boss，认为处于战斗状态
	if enemies.size() > 0 or boss_enemies.size() > 0:
		enemy_detected = true
		return BattleState.BATTLE
	else:
		enemy_detected = false
		return BattleState.IDLE

## 处理战斗状态变化
func _handle_battle_state_change(new_state: BattleState) -> void:
	match new_state:
		BattleState.BATTLE:
			if current_battle_state == BattleState.IDLE:
				# 从空闲进入战斗
				EventBus.push_event("battle_start")
				print("战斗开始")
		BattleState.IDLE:
			if current_battle_state == BattleState.BATTLE:
				# 从战斗进入空闲
				EventBus.push_event("battle_end")
				print("战斗结束")

## 手动设置战斗状态（用于测试）
func set_battle_state(state: BattleState) -> void:
	if state != current_battle_state:
		_handle_battle_state_change(state)
		current_battle_state = state

## 获取当前战斗状态信息
func get_battle_state_info() -> Dictionary:
	return {
		"current_state": current_battle_state,
		"enemy_detected": enemy_detected,
		"battle_state_duration": battle_state_duration
	}

## 检查是否在战斗中
func is_in_battle() -> bool:
	return current_battle_state == BattleState.BATTLE 
